﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace PJ.Data
{
    /// <summary>
    /// EntityFragmentPICProvider : Persist In Cache data provider
    /// </summary>
    /// <typeparam name="I">Object to provide interface type</typeparam>
    /// <typeparam name="C">Object to provide concrete class type</typeparam>
    public abstract class EntityFragmentPICProvider<I, C> : ObjectPICProvider<I, C>, IEntityFragmentProvider<I>
        where C : BaseEntityFragmentData, I, new()
        where I : class, IEntityFragmentData
    {
        public EntityFragmentPICProvider(ICacheManager cache)
            : base(cache)
        {
        }

        public virtual IEnumerable<string> GetFragments(string parentId)
        {
            if (parentId == null)
                throw new ArgumentNullException();
            return (from d in DataObjects where d.ParentId == parentId select d.GlobalId);
        }

        public virtual IEnumerable<string> CachedGetFragments(string parentId)
        {
            return GetFragments(parentId);
        }

        public virtual IEnumerable<string> FindFragments(string parentId)
        {
            if (parentId == null)
                throw new ArgumentNullException();
            var query = (from d in DataObjects where d.ParentId == parentId select d.GlobalId);
            if (query.Count() == 0)
                return null;
            else
                return query.AsEnumerable();
        }

        public virtual IEnumerable<string> CachedFindFragments(string parentId)
        {
            return FindFragments(parentId);
        }

        public int FragmentsCount(string parentId)
        {
            return DataObjects.Count(p => p.ParentId == parentId);
        }

    }
}
